package logic

import (
	"context"
	"fmt"
	"user_srv/models/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 实名认证
func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	// todo: add your logic here and delete this line

	auth := mysql.RealName{
		UserId:   int(in.UserId),
		RealName: in.RealName,
		IdCard:   in.IdCard,
	}
	var err error
	if err = auth.RealNameList(); err != nil {
		logx.Error("实名认证失败")
		return nil, fmt.Errorf("实名认证失败")
	}

	if auth.ID > 0 {
		logx.Error("实名用户不存在")
		return nil, fmt.Errorf("实名用户不存在")
	}

	if !pkg.AuthRealName(in.IdCard, in.RealName) {
		logx.Error("第三方调用失败")
		return nil, fmt.Errorf("第三方调用失败")
	}

	if err = auth.RealNameAdd(); err != nil {
		logx.Error("实名认证添加失败")
		return nil, fmt.Errorf("实名认证添加失败")
	}

	return &user.RealNameResponse{}, nil
}
